package dq.study.nio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;

/**
 * @author dongqun
 * @version 1.0
 * @description ${description}
 * @date 2019/8/29 14:58
 */
public class NioServer {

    public static void main(String[] args) {
        try {
            ServerSocketChannel channel = ServerSocketChannel.open();
            channel.bind(new InetSocketAddress(12346));
            channel.configureBlocking(false);
            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_ACCEPT);//serverSocketChannel对accept事件感兴趣
            int i;
            while ((i = selector.select()) > 0) {
                System.out.println(i);
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    if (key.isValid()) {
                        if (key.isAcceptable()) {
                            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                            SocketChannel sc = ssc.accept();
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println("客户机" + sc.socket().getInetAddress().getHostName() + "-" + sc.socket().getPort() + "连接成功");
                        } else if (key.isReadable()) {
                            SocketChannel channel1 = (SocketChannel) key.channel();
                            CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
                            ByteBuffer buffer = ByteBuffer.allocate(50);
                            try {
                                channel1.read(buffer);
                            } catch (IOException e) {
                                System.out.println("客户端：" + channel1.socket().getInetAddress().getHostName() + ":" + channel1.socket().getPort() + " 已断开连接");
                                channel1.close();
                                continue;
                            }
                            buffer.flip();
                            String msg = decoder.decode(buffer).toString();
                            CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
                            channel1.write(encoder.encode(CharBuffer.wrap("S:  " + msg)));
                        }
                    }
                    it.remove();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
